<?php

namespace backend\controllers;

use backend\models\PayUserDiscount;
use Yii;
use backend\models\SysUserDesigner;
use backend\models\SysUserDesignerSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use \yii\web\Response;
use yii\helpers\Html;
use common\models\UserInfo;
use yii\web\ForbiddenHttpException;
use liangzoe\mobilesmser\TextSmser;
use backend\models\UserInvite;
use yii\db\ActiveRecord;
use frontend\models\UserInfoEx;
use backend\models\PrfConfig;
use backend\models\LogUserScore;

/**
 * SysUserDesignerController implements the CRUD actions for SysUserDesigner model.
 */
class SysUserDesignerController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                    'bulk-delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}


    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('user-designer')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all SysUserDesigner models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SysUserDesignerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,false,"");
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


    /**
     * Displays a single SysUserDesigner model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $request = Yii::$app->request;
        if($request->isAjax){
            Yii::$app->response->format = Response::FORMAT_JSON;
            return [
                    'title'=> Yii::t('app', "Sys User Designers View"),
                    'content'=>$this->renderPartial('view', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Edit',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])
                ];
        }else{
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }
    }

    /**
     * Creates a new SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $model = new SysUserDesigner();

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> "Create new SysUserDesigner",
                    'content'=>$this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])

                ];
            }else if($model->load($request->post()) && $model->save()){
                return [
                    'forceReload'=>'true',
                    'title'=> "Create new SysUserDesigner",
                    'content'=>'<span class="text-success">Create SysUserDesigner success</span>',
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                            Html::a('Create More',['create'],['class'=>'btn btn-primary','role'=>'modal-remote'])

                ];
            }else{
                return [
                    'title'=> "Create new SysUserDesigner",
                    'content'=>$this->renderPartial('create', [
                        'model' => $model,
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','type'=>"submit"])
                ];
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->uid]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

    }

    /**
     * Updates an existing SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $model = $this->findModel($id);
        $model->setScenario('update');
        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            if($request->isGet){
                return [
                    'title'=> Yii::t('app', "Sys User Designers"),
                    'content'=>$this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','id'=>'designer_audit_btn','type'=>"submit"])
                ];
            }else if($model->load($request->post())){      	
            	if($request->post() !== null && $request->post('SysUserDesigner')!== null && isset($request->post('SysUserDesigner')['audit_state'])){
            		
            		$model->audit_time = time();
            		$model->audit_uid = Yii::$app->user->id;
            		$model->audit_state=$request->post('SysUserDesigner')['audit_state'];
            		if($request->post('SysUserDesigner')['audit_state'] == 1){//审核通过
            			$this->_invite_code($id);
            			//送积分
            			$logUserScore_mod = new LogUserScore();
            			$logUserScore_mod -> designerPoint($id);
            		}
            	}
            	if ($model->save())
            	{
            		///删除user_info_ex的邀请码数据
            		$invite_f_info = UserInfoEx::findOne(['user_id'=>$id,'u_key'=>'invite_f']);
            		if($invite_f_info)
            			$invite_f_info->delete();

        	        $model_user = UserInfo::findOne(['id'=>$id]);
        	        if($model->audit_state == 1){//审核通过
        	            $model_user->user_type = '3';
        	            $message = "您在JAJAHOME平台申请的VIP会员已通过！下单可享受各种折扣优惠。邀请好友购买，可返丰厚佣金。";
        	        }
        	        if($model->audit_state == 2){
        	            $model_user->user_type = '1';
        	            $message = "您的VIP会员申请未通过，原因是：".$model->audit_memo;
        	        }
        	        if ($model_user->save())
        	        {
        	            $mobile = $model_user->tel;
        	            $smser = new TextSmser();
        	            $smser->sendSMS($mobile, $message);
        	        }
        	        return [
        	            'forceReload'=>'true',
        	            'title'=> Yii::t('app', "Sys User Designers View"),
        	            'content'=>$this->renderPartial('view', [
        	                'model' => $this->findModel($id),
        	            ]),
        	            'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
        	            Html::a('Edit',['update','id'=>$id],['class'=>'btn btn-primary','role'=>'modal-remote'])
        	        ];
            	}
            }else{
                 return [
                    'title'=> Yii::t('app', "Sys User Designers"),
                    'content'=>$this->renderPartial('update', [
                        'model' => $this->findModel($id),
                    ]),
                    'footer'=> Html::button('Close',['class'=>'btn btn-default pull-left','data-dismiss'=>"modal"]).
                                Html::button('Save',['class'=>'btn btn-primary','id'=>'designer_audit_btn','type'=>"submit"])
                ];
            }
        }else{
            /*
            *   Process for non-ajax request
            */
            if ($model->load($request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->uid]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }
    }
	//补充邀请码
	 public function _invite_code($id){
	 	$invite_info = UserInvite::findOne($id);
	 	if(!$invite_info || ($invite_info && !$invite_info['invite'])){
	 		$invite_f_info = UserInfoEx::findOne(['user_id'=>$id,'u_key'=>'invite_f']);
	 		if($invite_f_info){
	 			$new_invite = new UserInvite();
	 			$new_invite->setScenario('update');
	 			$new_invite->uid = $id;
	 			$new_invite->invite = TextSmser::random_mix(6);
	 			$new_invite->invite_f = $invite_f_info['u_value'];
	 			$new_invite->save();
	 		}
	 	}
	 }
    /**
     * Delete an existing SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $request = Yii::$app->request;
        $this->findModel($id)->delete();

        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>true];
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }


    }

     /**
     * Delete multiple existing SysUserDesigner model.
     * For ajax request will return json object
     * and for non-ajax request if deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionBulkDelete()
    {
        $request = Yii::$app->request;
        $pks = $request->post('pks'); // Array or selected records primary keys
        foreach (SysUserDesigner::findAll(json_decode($pks)) as $model) {
            $model->delete();
        }


        if($request->isAjax){
            /*
            *   Process for ajax request
            */
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ['forceClose'=>true,'forceReload'=>true];
        }else{
            /*
            *   Process for non-ajax request
            */
            return $this->redirect(['index']);
        }

    }
    //VIP会员权限管理index
    public function actionAuthorityManagement()
    {
        $searchModel = new SysUserDesignerSearch();
        
        $dataProvider = $searchModel->search2(Yii::$app->request->queryParams,true,"");

        $t = PayUserDiscount::find()->select(['user_type','user_type_class','discount_rate','post_sales_service'])->distinct()->orderBy(['discount_rate' => SORT_DESC])->asArray()->all();
        $user_type=[];
        $ps_service = [0=>'含服务',1=>'不含服务'];
        foreach ($t as $value)
        {
            if (!isset($user_type[$value['user_type']]))
            {
                $user_type[$value['user_type']]=[];
            }
            if (!in_array($value['user_type_class'], $user_type[$value['user_type']]))
            {
                $user_type[$value['user_type']][count($user_type[$value['user_type']])]=$value['user_type_class'].'（折扣：'.$value['discount_rate']. ' ' .$ps_service[$value['post_sales_service']] .'）';
            }
        }
        return $this->render('AuthorityManagement',[
            'user_type'=>$user_type,
            'searchModel'=>$searchModel,
            'dataProvider'=>$dataProvider,
        ]);
    }
    //VIP会员权限管理提交数据处理
    public function actionDesignerAuthority(){
        $userType = UserInfo::find()->select(['user_type','user_type_class'])->where(['id'=>Yii::$app->request->post('uid')])->asArray()->one();
        if ($userType["user_type"] == 3 && $userType['user_type_class'] == 5 ) {
            $isDesigner = true;
        } else {
            $isDesigner = false;
        }
		if(!\Yii::$app->user->can('user-designer')){
			throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
		}
        if (isset($_POST['uid'])&&isset($_POST['q'])){
            $uid=intval(Yii::$app->request->post('uid'));
            $model_userinfo=UserInfo::findOne(['id'=>$uid]);
            $model=SysUserDesigner::findOne(['uid'=>$uid]);
            if ($model->invite['invite_f']=='888888'){
                $model_invite=UserInvite::findOne(['uid'=>$uid]);
            }
            else{
                $model_invite=null;
            }

            if (Yii::$app->request->post('q')=='get-info'){

                $user_def=[
                    '0'=>'游客',
                    '1'=>'普通用户',
                    '2'=>'VIP会员(申请中)',
                    '3'=>'认证VIP会员',
                    '4'=>'装饰公司',
                    '5'=>'城市运营商',
                    '6'=>'协会',
                    '7'=>'服务商',
                    '8'=>'内部员工'
                ];
                $t=ActiveRecord::findBySql('SELECT DISTINCT user_type FROM `pay_user_discount`')->asArray()->all();
                foreach ($t as $value)
                {
                    if(in_array($value['user_type'], [3,4,7])){
                        $user_type_0[$value['user_type']]=$user_def[$value['user_type']];
                    }
                }
                return $this->renderAjax('_AMform',[
                    'user_type_0'=>$user_type_0,
                    'model_invite'=>$model_invite,
                    'model_userinfo'=>$model_userinfo,
                    'isDesigner'=>$isDesigner
                ]);
            }

            elseif (Yii::$app->request->post('q')=='set-info')
            {
                $getPost = Yii::$app->request->post();
//                $userClass= UserInfo::find()->select(['user_type_class'])->where(['id'=>Yii::$app->request->post('uid')])->asArray()->one();
//                if($getPost['UserInfo']['user_type'] == 3 && $userClass['user_type_class'] != 5){
//                    $getPost['UserInfo']['user_type_class'] = 1;
//                }
                if ($getPost['UserInfo']['user_type'] != $model_userinfo->user_type) {
                    $getPost['UserInfo']['user_type_class'] = 1;
                }
                if ($model_userinfo->load($getPost)&&$model_userinfo->validate()&&$model_userinfo->save())
                {
                    $userinfo_save=true;
                }
                $userInvite_save=null;
                if ($model_invite&&$model_invite->load($getPost)&&$model_invite->validate()&&$model_invite->save())
                {
                    $userInvite_save=true;
                }
                if ($userinfo_save&&($userInvite_save==null)||$userinfo_save&&$userInvite_save)
                {
                    return $this->redirect(['sys-user-designer/authority-management']);
                }
                else
                {
                    echo '出错';
                }
            }
        }
    }
    /**
     * Finds the SysUserDesigner model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SysUserDesigner the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
    	$model = SysUserDesigner::find()->where("uid={$id}")->joinWith('userinfo')->one();
    	//$model = SysUserDesigner::findOne($id)
        if ($model !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
